package org.springcloud.plugin.framework.strategy.rule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.PredicateKey;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.ZoneAvoidancePredicate;
import org.springcloud.plugin.framework.adapter.CoreAdapter;
import org.springcloud.plugin.framework.strategy.adapter.DiscoveryEnabledAdapter;

import javax.annotation.Nullable;

public class DiscoveryEnabledZoneAvoidancePredicate extends ZoneAvoidancePredicate {

    protected CoreAdapter coreAdapter;
    protected DiscoveryEnabledAdapter discoveryEnabledAdapter;

    public DiscoveryEnabledZoneAvoidancePredicate(IRule rule, IClientConfig clientConfig) {
        super(rule, clientConfig);
    }

    @Override
    public boolean apply(@Nullable PredicateKey input) {
        boolean enabled = super.apply(input);
        if (!enabled) {
            return false;
        }
        return apply(input.getServer());
    }

    protected boolean apply(Server server) {
        if (discoveryEnabledAdapter == null) {
            return true;
        }
        return discoveryEnabledAdapter.apply(server);
    }

    public void setPluginAdapter(CoreAdapter coreAdapter) {
        this.coreAdapter = coreAdapter;
    }

    public void setDiscoveryEnabledAdapter(DiscoveryEnabledAdapter discoveryEnabledAdapter) {
        this.discoveryEnabledAdapter = discoveryEnabledAdapter;
    }
}
